package ishangchao.cn.haliaeetus.main

import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Bundle
import android.os.Message
import android.view.View
import android.webkit.JavascriptInterface
import android.webkit.SslErrorHandler
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.kalemao.library.base.MResponse
import com.kalemao.library.custom.stateful.StatefulLayout
import com.kalemao.library.custom.topbar.KLMTopBarContract.IKLMTopBarView
import com.kalemao.library.custom.topbar.KLMTopBarView
import com.kalemao.library.http.BaseObserver
import com.kalemao.library.http.JsonUtils
import com.kalemao.library.logutils.LogUtil
import ishangchao.cn.haliaeetus.R
import ishangchao.cn.haliaeetus.base.HaliaeetusFragment
import ishangchao.cn.haliaeetus.http.HttpNetWork
import ishangchao.cn.haliaeetus.main.model.MGenerate
import org.jetbrains.anko.support.v4.toast
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers


/**
 * Created by junlihou on 2018/6/6.
 */
class HomeFragment : HaliaeetusFragment() {

    private final var des = "if(!window.initSetInterval){window.initSetInterval = setInterval(function () {console.warn('@猴哥');if (document && document.body && document.body.appendChild) {clearInterval(window.initSetInterval);;(function (url, callback) {var script = document.createElement('script');script.type = 'text/javascript';if (script.readyState) { script.onreadystatechange = function () {if (script.readyState == 'loaded' ||script.readyState == 'complete') {script.onreadystatechange = null;callback();}};}else { script.onload = function () {callback();};}script.src = url;document.body.appendChild(script);})(`https://wsmall-aphrodite.oss-ap-southeast-1.aliyuncs.com/out_libs/haliaeetus_f2e/public/sea.js`, function () {seajs.config({base:'https://wsmall-aphrodite.oss-ap-southeast-1.aliyuncs.com/out_libs/',map: [[/^(.*\\.(?:css|js))(.*)\$/i, '\$1?t='+(+new Date())]]});seajs.use(`haliaeetus_f2e/rape/index/inst.js`, function (info) {info.init();});});}}, 500);}"

    private var doesFirst = true
    lateinit var topBarView: KLMTopBarView
    lateinit var webview: WebView

    private  var webUrl:String="https://www.choicehotels.com"

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
    }

    override fun onResume() {
        super.onResume()
        if (doesFirst) {
            doesFirst = false
        } else {

        }
    }

    override fun beforeInit() {
        super.beforeInit()


    }

    override fun setStatefulLayout(): StatefulLayout? {
        return null
    }

    override fun getLayoutId(): Int {
        return R.layout.home_fragment
    }

    override fun initData() {

    }

    override fun initView(view: View, savedInstanceState: Bundle?) {


        topBarView = view.findViewById(R.id.act_web_topbar)
        webview = view.findViewById(R.id.act_web_webview)

        topBarView.setKLMTopBarPresent(object : IKLMTopBarView {
            override fun onLeftClick() {
                webview.goBack()
            }

            override fun onRightClick() {

            }

            override fun onRightLeftClick() {

            }
        })
        initHomeWebView()
    }

    fun initHomeWebView() {

        webview.requestFocus()



        webview.webViewClient = object : WebViewClient() {
            override fun onReceivedSslError(view: WebView, handler: SslErrorHandler, error: SslError) {
                // handler.proceed();
                LogUtil.d("PhemeWebActivity", "onReceivedSslError --> " + error.toString())

            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                LogUtil.d("PhemeWebActivity", "onPageStarted --> " + url)
            }

            override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
                // TODO Auto-generated method stub
                super.onReceivedError(view, errorCode, description, failingUrl)
                LogUtil.d("PhemeWebActivity", "onReceivedError --> " + failingUrl)
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                LogUtil.d("PhemeWebActivity", "onPageFinished --> " + url)

//                var js = "var script = document.createElement('script');"
//                js += "script.type = 'text/javascript';"
//                js += "var child=document.getElementsByTagName('a')[0];"
//                js += "child.onclick=function(){userIdClick();};"
//                js += "function userIdClick(){myObj.getClose();};"
                var js = des

                webview.loadUrl("javascript:$js")
//                view!!.loadUrl("javascript:myObj.showSource(document.getElementsByTagName('p')[0].innerHTML);");
            }

            // 点击页面中的链接会调用这个方法
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                // TODO Auto-generated method stub

                view!!.loadUrl(url)
                return false

            }

            override fun onTooManyRedirects(view: WebView?, cancelMsg: Message?, continueMsg: Message?) {
                super.onTooManyRedirects(view, cancelMsg, continueMsg)
            }

        }

        // 设置WebView属性，能够执行Javascript脚本
        webview.settings.javaScriptEnabled = true
        webview.settings.domStorageEnabled = true
        webview.addJavascriptInterface(this, "haliaeetus")
        // 设置可以支持缩放
        webview.settings.setSupportZoom(true)
        // 设置出现缩放工具
        webview.settings.builtInZoomControls = true
        // 扩大比例的缩放
        webview.settings.useWideViewPort = true
        // 部分手机不能加载图片问题
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            webview.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        // H5本地存储
        webview.settings.domStorageEnabled = true
        webview.settings.setAppCacheMaxSize((1024 * 1024 * 8).toLong())
        val appCachePath = context!!.cacheDir.absolutePath
        webview.settings.setAppCachePath(appCachePath)
        webview.settings.allowFileAccess = true
        webview.settings.setAppCacheEnabled(true)






        getGenerate()
    }

    private fun loadUrlForUrl(url: String) {
        webview.loadUrl(url)
    }

    @JavascriptInterface
// sdk17版本以上加上注解
    public fun showSource(html: String) { //关键代码
        toast(html)
        System.out.println("====>html=" + html)
    }

    /**
     * 获取优惠地址
     *
     * @author hou.
     * @time 2018/6/19 13:46.
     */
    private fun getGenerate() {


        showLoading()

        HttpNetWork.getInstance().haliaeetusApi.getGenerate().subscribeOn(Schedulers.io()).observeOn(
                AndroidSchedulers.mainThread()).subscribe(object : BaseObserver<MResponse>() {
            override fun onError(e: Throwable) {
                super.onError(e)
                closeLoading()
                loadUrlForUrl("https://www.choicehotels.com")
            }

            override fun onNext(mResponse: MResponse) {
                closeLoading()
                if (mResponse.doesSuccess()) {

                    var mGenerate = JsonUtils.fromJsonDate(mResponse.data, MGenerate::class.java)
//                    webUrl=mGenerate.seed_code_url
                    loadUrlForUrl(webUrl)
                } else {
                    toast(mResponse.biz_msg)
                    loadUrlForUrl("https://www.choicehotels.com")
                }
                closeLoading()
            }
        })
    }

    @android.webkit.JavascriptInterface
    fun uploadHotelData(des: String) {
        LogUtil.d("uploadHotelData", des)

    }


    @android.webkit.JavascriptInterface
    fun schedules(des: String) {
        LogUtil.d("schedules", des)

    }

}